<template>
    <div>
        <div v-show="!noData" class="searchbar">
            <div class="weui-search-bar" id="searchBar" v-show='showSearch'>
                <form class="weui-search-bar__form">
                    <div class="weui-search-bar__box">
                        <i class="weui-icon-search"></i>
                        <input type="search" class="weui-search-bar__input" id="searchInput" placeholder="搜索" required="">
                        <a class="weui-icon-clear" id="searchClear"></a>
                    </div>
                    <label @click='toSearch' class="weui-search-bar__label" id="searchText" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);">
                        <i class="weui-icon-search"></i>
                        <span>搜索</span>
                    </label>
                </form>
                <a class="weui-search-bar__cancel-btn" id="searchCancel">取消</a>
            </div>
        </div>
        <ul class="project-list" v-show="!noData">
            <li transition="item" v-for="(index, item) in items" :class="{'top': item.top==1}">
                <!-- <a @click="toMsgList(item.team_id, item.project_id, item.name ,item.role_id, totalUnreadMsg)"> -->

                  <a href="dmsaas://ProjectDetail?projectName={{encodeUrlName(item.name)}}&teamId={{item.team_id}}&projectId={{item.project_id}}&roleId={{item.role_id}}&user_id={{userId}}&unreadmsg={{item.unread_msg_count}}&memberCount={{item.number}}">
                    <div class="logo"><img :src="item.logo" alt=""><span class="red-dot" v-show="item.unread_msg_count">{{item.unread_msg_count}}</span></div>
                    <div class="info">
                        <h2>{{item.name}}</h2>
                        <p class="p1">{{item.first_msg || '暂无消息'}}</p>
                        <p class="p2"><span><i class="icon icon-1 bg_sprite"></i>{{item.number}}人</span><span><i class="icon icon-2 bg_sprite"></i>{{item.pro_name | strEllipsis}}</span></p>
                        <span class="time" v-show="item.first_msg_time != 0">{{item.first_msg_time}}</span>
                    </div>
                </a>
                <div class="opt">
                    <span v-touch-ripple v-if="item.top==1" @click="setToUnTop(item.team_id, item.project_id, index)" class="btn_1">取消置顶</span>
                    <span v-touch-ripple v-if="item.top==0" @click="setToTop(item.team_id, item.project_id, index)" class="btn_1">置顶</span>
                    <span v-touch-ripple v-if="status==1&&item.stop_button == 1" @click="setToStop(item.team_id, item.project_id)" class="btn_2">结束</span>
                    <span v-touch-ripple v-if="status==2&&item.stop_button == 1" @click="setToOpen(item.team_id, item.project_id)" class="btn_3">开启</span>
                </div>
            </li>
        </ul>
        <div class="mod-empty" v-show="noData">
            <div class="bg_sprite icon icon_1"></div>
            <p class="tip">当前无项目</p>
        </div>
        <div v-show="loading">
          <div class="weui-mask"></div>
          <div class="weui-toast">
              <i class="weui-loading weui-icon_toast"></i>
              <p class="weui-toast__content">数据加载中</p>
          </div>
        </div>
        <div  v-show="busy" class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
        </div>
    </div>
</template>

<script>
    var s;
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
     import $ from 'zepto'
     import SW from 'swiped'
     import * as util from 'js/util.js'
     import widget from 'gapi/widget'
     import cache from 'gapi/cache'
     import searchPage from 'clientApi/searchPage'
     import clientInfoApi from 'clientApi/clientInfo'
     import commonPage from 'clientApi/commonPage'
     import projectApi from 'clientApi/projectApi'
     import userCenterApi from 'clientApi/userCenterApi'

    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        filters : {
            strEllipsis : function(str) {
                if (str.length > 10) {
                    return str.substring(0, 10) + '...'
                } else {
                    return str;
                }
            }
        },
        data: function(){
            return{
                showSearch: true,
                busy: false,
                loading: false,
                noData: false,
                items: [],
                status: '', //tab状态  1:进行中 2 已结束
                userId: '',
                totalUnreadMsg: '',
                user_id:''
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
              userCenterApi.getUserInfo(function(info){
                if(info){
                  this.userId = info.userId
                }
              })
              cache.deleteCache('projectInfoData')
            },
            encodeUrlName (name){
              return encodeURIComponent(name)
            },
            //跳转到 消息列表 
            toMsgList (team_id, project_id, project_name,role_id, unreadmsg){
              // let encodeUrl = encodeURIComponent(`teamId=${team_id}&projectId=${project_id}&projectName=${project_name}&roleId=${role_id}&unreadmsg=${unreadmsg}`)    
              let encodeUrl = encodeURIComponent(`teamId=${team_id}`)
              location.href = `dmsaas://ProjectDetail?urdData=${encodeUrl}`
            },
            //获取tab列表数据
            getCTabListData (backData){
                this.noData = false;
              util.ajax({
                      url:'/project/list/get',
                      type:'POST',
                      data:{
                          team_id : 0,//默认0
                          status : this.status
                      },
                      timeout:10000,
                      beforeSend: () => {
                        this.loading = true
                      },
                      success:(result) => {
                        console.log(JSON.stringify(result))
                          if(result.errno == 0){
                              this.items = result.data.list
                            if(!result.data.list.length){//没有项目
                              this.noData = true
                              commonPage.dataDownloadFinished()
                              return
                            }
                            this.totalUnreadMsg = result.data.unReadCount// 总共未读的消息数
                            //通知客户端sqlite 更新列表数据
                            searchPage.updateProjectList(['name'], result.data.list, this.status, (searchResult) => {})

                            //1 cache list data (no neeed do this because use sqlite)
                            // cache.setCache('projectlistData', result.data.list, 60 * 60 * 10)

                            //2 reorder by top ==1  //server do it (排序规则 置顶 > 最新消息时间)
                            // this.items.sort((a, b) => b.top - a.top)

                            //3 swiped init
                            setTimeout(()=> { //trick for init swipe after template rendered use setTimeout
                                s =  Swiped.init({
                                    query: '.project-list a',
                                    list: true,
                                    right: 184,
                                });
                                if (!s.forEach) {
                                    if (this.items[0].stop_button != 1) {
                                        s.right = 92;
                                    }
                                } else {
                                    s.forEach((item, index) => {
                                        if (this.items[index].stop_button != 1) {
                                            item.right = 92;
                                        }

                                    })
                                }
                            },10)
                            // 4 notify data downloaded to native
                            commonPage.dataDownloadFinished()

                          }
                      },
                      error: (xhr, status) => {
                        if(status=='timeout'){
                            widget.toast('网络请求超时');
                            commonPage.dataDownloadFinished();
                        }else{
                            if(xhr.status==400){
                                var err=JSON.parse(xhr.responseText);
                                widget.toast(err.message);
                                return;
                            }
                        }
                      },
                      complete: () => {
                        this.loading = false
                      },
                      noNetwork: () => {
                          widget.toast('网络连接失败，请检查网络,请检查您的网络')
                          //get data from sqlite
                          projectApi.getLocalListData(this.status, (data) => {
                            this.items = JSON.parse(data)
                            //swiped init
                            setTimeout(()=> { //trick for init swipe after template rendered use setTimeout
                                s =  Swiped.init({
                                    query: '.project-list a',
                                    list: true,
                                    right: 184,
                                });
                                if (!s.forEach) {
                                    if (this.items[0].stop_button != 1) {
                                        s.right = 92;
                                    }
                                } else {
                                    s.forEach((item, index) => {
                                        if (this.items[index].stop_button == 1) {
                                            item.right = 92;
                                        }
                                    })
                                }
                            },10)
                            //notify data downloaded to native
                            commonPage.dataDownloadFinished()
                          })
                      }
                  })
            },
            //加载更多
            loadMore (){
                this.busy = true
                setTimeout(() => { //todo : replace with ajax fetch api data
                    for(let i= this.pageIndex * this.pageSize; i < (this.pageIndex + 1) * this.pageSize; i++){
                        this.items.push({
                            "id": i,
                            "name": `Project ${i}`,
                            "number": "100",
                            "pro_name": '斗米兼职',
                            "first_msg": '考勤：同学还有10分钟就要上班了，不要忘...',
                            "msg_count": 10
                        })
                        this.busy = false

                    }
                    this.pageIndex++
                },1000)
            },
            //go to search page
            toSearch (){//todo 优化
                location.href= `dmsaas://ProjectSearch?status=${this.status}`
            },
            //置顶
            setToTop (team_id, project_id, index){
                /*if (this.status == 2) {
                    widget.toast('请开启项目后操作');
                    return;
                }*/
                //call api to server
                util.ajax({
                    url:'/project/top/set',
                    type:'POST',
                    data:{
                        team_id : team_id,
                        project_id : project_id,
                        action: 1,
                    },
                    timeout:10000,
                    success:(result) => {
                        // alert(JSON.stringify(obj))
                        if(result.errno == 0){
                          this.items[index].top = 1

                        //   Array.prototype.move = function(from, to) {
                        //     this.splice(to, 0, this.splice(from, 1)[0]);
                        // };
                          //将item置为第一个元素
                          let top_item_array = this.items.splice(index, 1)
                          this.items.unshift(top_item_array[0]);

                          //scroll to top if top items' height
                          $(window).scrollTop(0)

                          // close swiped
                          s.forEach((item) => {
                            item.close()
                          })

                          // widget.toast('置顶成功')
                        }
                    },
                    error: (xhr, status) => {
                      var toastStr = ''
                      if(status == 'timeout'){
                        toastStr = '网络请求超时'
                      }else{
                        toastStr = '服务器异常'
                      }

                      widget.toast(toastStr)
                    },
                    noNetwork: () => {
                      widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            //取消置顶
            setToUnTop (team_id, project_id, index){
              //call api to server
              util.ajax({
                  url:'/project/top/set',
                  type:'POST',
                  data:{
                      team_id : team_id,
                      project_id : project_id,
                      action: 0,
                  },
                  timeout:10000,
                  success:(result) => {
                      // alert(JSON.stringify(obj))
                      if(result.errno == 0){
                        this.items[index].top = 0

                        this.items.sort((a,b) => b.top - a.top) //非置顶项的第一个
                        // close swiped
                        s.forEach((item) => {
                          item.close()
                        })
                        // widget.toast('取消置顶成功')
                      }
                  },
                  error: (xhr, status) => {
                      // error
                      var toastStr = ''
                      if(status == 'timeout'){
                        toastStr = '网络请求超时'
                      }else{
                        toastStr = '服务器异常'
                      }

                      widget.toast(toastStr)
                  },
                  noNetwork: () => {
                      widget.toast('网络连接失败，请检查网络')
                  }
              })
            },
            //开启项目
            setToOpen (team_id, project_id){
              //call api to server
              util.ajax({
                  url:'/project/status/action',
                  type:'POST',
                  data:{
                      team_id : team_id,
                      project_id : project_id,
                      action: 1,
                  },
                  timeout:10000,
                  success:(result) => {
                      // alert(JSON.stringify(obj))
                      if(result.errno == 0){
                        // close swiped
                        if (s.forEach) {
                            s.forEach((item) => {
                                item.close()
                            })
                        } else {
                            s.close();
                        }
                          this.getCTabListData()
                        //todo : switch to 已结束tab ?
                        //通知客户端切换tab & 刷新列表
                      }
                  },
                  error: (xhr, status) => {
                      // error
                     var toastStr = ''
                      if(status == 'timeout'){
                        toastStr = '网络请求超时'
                      }else{
                        toastStr = '服务器异常'
                      }

                      widget.toast(toastStr)
                  },
                  noNetwork: () => {
                      widget.toast('网络连接失败，请检查网络')
                  }
              })
            },
            //结束项目
            setToStop (team_id, project_id){
              //call api to server
              util.ajax({
                  url:'/project/status/action',
                  type:'POST',
                  data:{
                      team_id : team_id,
                      project_id : project_id,
                      action: 3
                  },
                  timeout:10000,
                  success:(result) => {
                      // alert(JSON.stringify(obj))
                      if(result.errno == 0){
                        // close swiped
                        if (s.forEach) {
                            s.forEach((item) => {
                                item.close() 
                            })
                        } else {
                            s.close();
                        }
                        this.getCTabListData()
                        //todo : switch to 已结束tab ?
                        //通知客户端切换tab & 刷新列表
                      }
                  },
                  error: (xhr, status) => {
                      // error
                    var toastStr = ''
                      if(status == 'timeout'){
                        toastStr = '网络请求超时'
                      }else{
                        toastStr = '服务器异常'
                      }

                      widget.toast(toastStr)
                  },
                  noNetwork: () => {
                      widget.toast('网络连接失败，请检查网络')
                  }
              })
            }
        },
        created(){ 
            this.init();
            commonPage.getWebViewID((data)=>{
              cache.setMemoryCache('jcIndexWebViewID',{'webViewID':data})
            }) 
        },
        ready(){
            //当前url tab参数
            this.status = util.getQueryString('status')
            //第一次进来拉取列表
            this.getCTabListData()
            //供客户端调用: 下拉刷新 & 其他页面返回到首页刷新列表
            window.loadData = this.getCTabListData

            cache.getCache('localityData', (data) => {
              console.log(data)
                if(!data){
                  console.log('请求')
                    commonPage.loadPageStatus('loading')
                    /*获取地区下拉选择列表，存放在缓存里*/ 
                    util.ajax({
                        url:'/common/geography/get',
                        type:'GET',
                        data:{
                            team_id:0,
                            project_id:0
                        },
                        timeout:10000,
                        success:(obj) => {
                            commonPage.loadPageStatus('loadSuccess')
                            if(obj.errno == 0){
                                cache.setCache('localityData', obj.data, 86400*30)
                            }else{
                                widget.toast(obj.errmsg)
                            }
                        },
                        error: (xhr, status) => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('服务器异常')
                        },
                        noNetwork: () => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('网络连接失败，请检查网络')
                        }
                    })
                }else{
                  console.log(88)
                  cache.setCache('localityData', data, 86400*30)
                }
            })
        }
    }


</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/project.css"></style>
<style>
    .item-move{
        /* applied to the element when moving */
        transition: transform .5s cubic-bezier(0.25, 0.5, 0.75, 1);
    }

</style>
